package com.example.service.impl;

import com.example.common.Result;
import com.example.common.PageResult;
import com.example.dto.HaircutPackageDTO;
import com.example.entity.HaircutPackage;
import com.example.entity.User;
import com.example.mapper.HaircutPackageMapper;
import com.example.service.HaircutPackageService;
import com.example.service.MemberDiscountService;
import com.example.util.UserContextUtil;
import com.example.vo.HaircutPackageVO;
import com.example.vo.DiscountInfoVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 理发套餐服务实现类
 */
@Slf4j
@Service
public class HaircutPackageServiceImpl implements HaircutPackageService {
    
    @Autowired
    private HaircutPackageMapper haircutPackageMapper;
    
    @Autowired
    private MemberDiscountService memberDiscountService;
    
    @Autowired
    private UserContextUtil userContextUtil;
    
    /**
     * 应用会员折扣信息到套餐VO
     */
    private void applyMemberDiscount(HaircutPackageVO packageVO) {
        try {
            // 获取当前用户信息
            User currentUser = userContextUtil.getCurrentUser();
            String memberLevel = "NORMAL"; // 默认普通用户
            
            if (currentUser != null && currentUser.getMemberLevel() != null) {
                memberLevel = currentUser.getMemberLevel();
            }
            
            // 计算会员折扣信息
            Result<DiscountInfoVO> discountResult = memberDiscountService.getMemberDiscountInfo(
                packageVO.getPackagePrice(), memberLevel);
            
            if (discountResult.getCode() == 200 && discountResult.getData() != null) {
                DiscountInfoVO discountInfo = discountResult.getData();
                
                // 设置折扣相关字段
                packageVO.setUserMemberLevel(memberLevel);
                packageVO.setMemberLevelName(discountInfo.getMemberLevelName());
                packageVO.setMemberDiscountRate(discountInfo.getDiscountRate());
                packageVO.setMemberDiscountPrice(discountInfo.getDiscountPrice());
                packageVO.setSavedAmount(discountInfo.getSavedAmount());
                packageVO.setDiscountDescription(discountInfo.getDiscountDescription());
                packageVO.setHasMemberDiscount(discountInfo.getHasDiscount());
                
                log.debug("应用套餐会员折扣 - 套餐: {}, 会员等级: {}, 原价: {}, 折扣价: {}, 节省: {}", 
                    packageVO.getPackageName(), memberLevel, packageVO.getPackagePrice(), 
                    discountInfo.getDiscountPrice(), discountInfo.getSavedAmount());
            }
        } catch (Exception e) {
            log.warn("应用套餐会员折扣失败，套餐ID: {}", packageVO.getId(), e);
            // 出错时设置默认值，不影响基本功能
            packageVO.setUserMemberLevel("NORMAL");
            packageVO.setMemberLevelName("普通用户");
            packageVO.setHasMemberDiscount(false);
        }
    }
    
    @Override
    @Transactional
    public Result<Void> addHaircutPackage(HaircutPackageDTO packageDTO) {
        try {
            // 参数校验
            if (packageDTO.getPackageName() == null || packageDTO.getPackageName().trim().isEmpty()) {
                return Result.error("套餐名称不能为空");
            }
            if (packageDTO.getPackagePrice() == null || packageDTO.getPackagePrice().compareTo(java.math.BigDecimal.ZERO) <= 0) {
                return Result.error("套餐价格必须大于0");
            }
            
            // 检查套餐名称是否已存在
            HaircutPackage existingPackage = haircutPackageMapper.selectByPackageName(packageDTO.getPackageName().trim(), null);
            if (existingPackage != null) {
                return Result.error("套餐名称已存在");
            }
            
            // 创建套餐实体
            HaircutPackage haircutPackage = new HaircutPackage();
            BeanUtils.copyProperties(packageDTO, haircutPackage);
            haircutPackage.setPackageName(packageDTO.getPackageName().trim());
            haircutPackage.setStatus(packageDTO.getStatus() != null ? packageDTO.getStatus() : 1);
            haircutPackage.setCreateTime(LocalDateTime.now());
            haircutPackage.setUpdateTime(LocalDateTime.now());
            haircutPackage.setDeleted(0);
            
            // 保存到数据库
            int result = haircutPackageMapper.insert(haircutPackage);
            if (result > 0) {
                log.info("新增理发套餐成功，套餐名称：{}", packageDTO.getPackageName());
                return Result.success();
            } else {
                return Result.error("新增套餐失败");
            }
        } catch (Exception e) {
            log.error("新增理发套餐失败", e);
            return Result.error("新增套餐失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public Result<Void> deleteHaircutPackage(Long id) {
        try {
            if (id == null) {
                return Result.error("套餐ID不能为空");
            }
            
            // 检查套餐是否存在
            HaircutPackage existingPackage = haircutPackageMapper.selectById(id);
            if (existingPackage == null) {
                return Result.error("套餐不存在");
            }
            
            // 软删除套餐
            int result = haircutPackageMapper.deleteById(id);
            if (result > 0) {
                log.info("删除理发套餐成功，套餐ID：{}", id);
                return Result.success();
            } else {
                return Result.error("删除套餐失败");
            }
        } catch (Exception e) {
            log.error("删除理发套餐失败", e);
            return Result.error("删除套餐失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public Result<Void> updateHaircutPackage(Long id, HaircutPackageDTO packageDTO) {
        try {
            if (id == null) {
                return Result.error("套餐ID不能为空");
            }
            
            // 参数校验
            if (packageDTO.getPackageName() == null || packageDTO.getPackageName().trim().isEmpty()) {
                return Result.error("套餐名称不能为空");
            }
            if (packageDTO.getPackagePrice() == null || packageDTO.getPackagePrice().compareTo(java.math.BigDecimal.ZERO) <= 0) {
                return Result.error("套餐价格必须大于0");
            }
            
            // 检查套餐是否存在
            HaircutPackage existingPackage = haircutPackageMapper.selectById(id);
            if (existingPackage == null) {
                return Result.error("套餐不存在");
            }
            
            // 检查套餐名称是否已被其他套餐使用
            HaircutPackage duplicatePackage = haircutPackageMapper.selectByPackageName(packageDTO.getPackageName().trim(), id);
            if (duplicatePackage != null) {
                return Result.error("套餐名称已存在");
            }
            
            // 更新套餐信息（价格不允许修改）
            HaircutPackage haircutPackage = new HaircutPackage();
            haircutPackage.setId(id);
            haircutPackage.setPackageName(packageDTO.getPackageName().trim());
            // 注意：管理员不能修改套餐价格，此处不设置价格字段
            haircutPackage.setPackageDescription(packageDTO.getPackageDescription());
            haircutPackage.setStatus(packageDTO.getStatus());
            haircutPackage.setUpdateTime(LocalDateTime.now());
            
            int result = haircutPackageMapper.updateById(haircutPackage);
            if (result > 0) {
                log.info("更新理发套餐成功，套餐ID：{}", id);
                return Result.success();
            } else {
                return Result.error("更新套餐失败");
            }
        } catch (Exception e) {
            log.error("更新理发套餐失败", e);
            return Result.error("更新套餐失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<HaircutPackageVO> getHaircutPackageById(Long id) {
        try {
            if (id == null) {
                return Result.error("套餐ID不能为空");
            }
            
            HaircutPackage haircutPackage = haircutPackageMapper.selectById(id);
            if (haircutPackage == null) {
                return Result.error("套餐不存在");
            }
            
            HaircutPackageVO packageVO = convertToVO(haircutPackage);
            
            // 应用会员折扣
            applyMemberDiscount(packageVO);
            
            log.info("查询套餐详情成功，套餐ID: {}, 套餐名称: {}, 会员等级: {}, 折扣价: {}", 
                id, packageVO.getPackageName(), packageVO.getUserMemberLevel(), packageVO.getMemberDiscountPrice());
            return Result.success(packageVO);
        } catch (Exception e) {
            log.error("查询理发套餐失败", e);
            return Result.error("查询套餐失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<List<HaircutPackageVO>> getAllHaircutPackages() {
        try {
            List<HaircutPackage> packages = haircutPackageMapper.selectAll();
            List<HaircutPackageVO> packageVOs = packages.stream()
                    .map(this::convertToVO)
                    .collect(Collectors.toList());
            return Result.success(packageVOs);
        } catch (Exception e) {
            log.error("查询所有理发套餐失败", e);
            return Result.error("查询套餐失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<List<HaircutPackageVO>> getAllEnabledHaircutPackages() {
        try {
            List<HaircutPackage> packages = haircutPackageMapper.selectAllEnabled();
            List<HaircutPackageVO> packageVOs = packages.stream()
                    .map(this::convertToVO)
                    .collect(Collectors.toList());
            
            // 为每个套餐应用会员折扣
            for (HaircutPackageVO packageVO : packageVOs) {
                applyMemberDiscount(packageVO);
            }
            
            log.info("查询启用套餐成功，返回{}条记录", packageVOs.size());
            return Result.success(packageVOs);
        } catch (Exception e) {
            log.error("查询启用的理发套餐失败", e);
            return Result.error("查询套餐失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<PageResult<HaircutPackageVO>> getHaircutPackagePage(int page, int size, String keyword) {
        try {
            // 设置分页参数
            PageHelper.startPage(page, size);
            
            // 查询数据
            List<HaircutPackage> packages = haircutPackageMapper.selectPage(keyword);
            PageInfo<HaircutPackage> pageInfo = new PageInfo<>(packages);
            
            // 转换为VO
            List<HaircutPackageVO> packageVOs = packages.stream()
                    .map(this::convertToVO)
                    .collect(Collectors.toList());
            
            // 构建分页结果
            PageResult<HaircutPackageVO> pageResult = new PageResult<>();
            pageResult.setRecords(packageVOs);
            pageResult.setTotal(pageInfo.getTotal());
            pageResult.setCurrent(page);
            pageResult.setSize(size);
            pageResult.setPages(pageInfo.getPages());
            
            return Result.success(pageResult);
        } catch (Exception e) {
            log.error("分页查询理发套餐失败", e);
            return Result.error("查询套餐失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<Boolean> checkPackageNameExists(String packageName, Long excludeId) {
        try {
            if (packageName == null || packageName.trim().isEmpty()) {
                return Result.success(false);
            }
            
            HaircutPackage existingPackage = haircutPackageMapper.selectByPackageName(packageName.trim(), excludeId);
            return Result.success(existingPackage != null);
        } catch (Exception e) {
            log.error("检查套餐名称是否存在失败", e);
            return Result.error("检查失败：" + e.getMessage());
        }
    }
    
    @Override
    @Transactional
    public Result<Void> updatePackageStatus(Long id, Integer status) {
        try {
            if (id == null) {
                return Result.error("套餐ID不能为空");
            }
            if (status == null || (status != 0 && status != 1)) {
                return Result.error("状态值无效");
            }
            
            // 检查套餐是否存在
            HaircutPackage existingPackage = haircutPackageMapper.selectById(id);
            if (existingPackage == null) {
                return Result.error("套餐不存在");
            }
            
            int result = haircutPackageMapper.updateStatus(id, status);
            if (result > 0) {
                log.info("更新理发套餐状态成功，套餐ID：{}，状态：{}", id, status);
                return Result.success();
            } else {
                return Result.error("更新状态失败");
            }
        } catch (Exception e) {
            log.error("更新理发套餐状态失败", e);
            return Result.error("更新状态失败：" + e.getMessage());
        }
    }
    
    @Override
    public Result<Void> enablePackage(Long id) {
        return updatePackageStatus(id, 1);
    }
    
    @Override
    public Result<Void> disablePackage(Long id) {
        return updatePackageStatus(id, 0);
    }
    
    @Override
    public Result<Object> getPackageStatistics() {
        try {
            int totalCount = haircutPackageMapper.countAll();
            int enabledCount = haircutPackageMapper.countEnabled();
            int disabledCount = totalCount - enabledCount;
            
            Map<String, Object> statistics = new HashMap<>();
            statistics.put("totalCount", totalCount);
            statistics.put("enabledCount", enabledCount);
            statistics.put("disabledCount", disabledCount);
            
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取套餐统计信息失败", e);
            return Result.error("获取统计信息失败：" + e.getMessage());
        }
    }
    
    /**
     * 将实体转换为VO
     */
    private HaircutPackageVO convertToVO(HaircutPackage haircutPackage) {
        HaircutPackageVO packageVO = new HaircutPackageVO();
        BeanUtils.copyProperties(haircutPackage, packageVO);
        packageVO.setStatusText(haircutPackage.getStatus() == 1 ? "启用" : "禁用");
        return packageVO;
    }
} 